package com.iweb.dao;

import com.iweb.pojo.Good;
import com.iweb.pojo.Pic;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class PicDaoImpl implements PicDao {

    private Connection connection;

    public PicDaoImpl(Connection connection) {
        this.connection = connection;
    }

    @Override
    public List<Pic> selectByGid(String gid) throws Exception {
        List<Pic> pics = new ArrayList<>();
        String sql = "select * from tb_pic where gid = ?";
        PreparedStatement pst = connection.prepareStatement(sql);
        pst.setObject(1,gid);
        ResultSet rs = pst.executeQuery();

        Pic pic = null;
        while (rs.next()){
            pic = createPic(rs);
            pics.add(pic);
        }
        return pics;
    }

    //找出所有某用户加入购物车的商品和数量
    @Override
    public List<Good> selectByUid(String aid) throws Exception {
        List<Good> gidsList=new ArrayList<>();
        String sql = "select gid,orders from tb_order where aid = ?";
        PreparedStatement pst = connection.prepareStatement(sql);
        pst.setObject(1,aid);
        ResultSet rs = pst.executeQuery();

        Pic pic = null;
        while (rs.next()){
            Good good=new Good();
            good.setGid(rs.getString(1));
            good.setOrders(rs.getInt(2));
            gidsList.add(good);

        }
        return gidsList;
        //返回good数组，其中good只包含gid和orders
    }

    //删除功能
    @Override
    public void deleteByUid(String aid,String gid) throws Exception {
        List<Good> gidsList=new ArrayList<>();
        String sql = "delete  from tb_order where aid = ? and gid=?";
        PreparedStatement pst = connection.prepareStatement(sql);
        pst.setObject(1,aid);
        pst.setObject(2,gid);
        pst.executeUpdate();

    }

    private Pic createPic(ResultSet rs)throws Exception {
        Pic pic = new Pic();
        pic.setPid(rs.getString(1));
        pic.setGid(rs.getString(2));
        pic.setPath(rs.getString(3));
        pic.setActive(rs.getString(4));
        return pic;
    }
}
